package com.sky.test;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

//@SpringBootTest
/**
 * 测试POI
 */
public class POITset {
    public static void main(String[] args) throws Exception {

        readExcel();
    }

    /**
     * 创建excel 并向里面写入内容
     */
    public static void writeExcel() throws  Exception{
        // TODO Auto-generated method stub
        //1.在内存中 创建excel类 对象
        XSSFWorkbook xxsworkbook = new XSSFWorkbook();
        //2.创建sheet (默认是没有的)
        XSSFSheet sheet = xxsworkbook.createSheet("员工信息表");
        //3.创建行
        XSSFRow row = sheet.createRow(2);
        //4.创建单元格 设置内容
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("性别");

        row=sheet.createRow(4);
        row.createCell(1).setCellValue("张三");
        row.createCell(2).setCellValue("男");

        row=sheet.createRow(5);
        row.createCell(1).setCellValue("张三");
        row.createCell(2).setCellValue("男");

        //5.内容保存到 磁盘中
        //创建文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\桌面\\员工消息表.xlsx"));
        //从内存中保存到磁盘
        xxsworkbook.write(fileOutputStream);

        //关闭流  防止占用
        xxsworkbook.close();
        fileOutputStream.close();
    }

    /**
     * 读excel 中的内容
     */
    public static void readExcel() throws Exception{
        //1.创建输入流对象
        FileInputStream fileInputStream = new FileInputStream(new File("D:\\桌面\\员工消息表.xlsx"));
        //2.创建excel对象
        XSSFWorkbook xxsworkbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = xxsworkbook.getSheetAt(0);
        Integer lastRowNum = sheet.getLastRowNum();
        for (int i = 0; i <= lastRowNum; i++) {
            System.out.println("第"+i+"行");
            XSSFRow row = sheet.getRow(i);
            if (row==null){
                continue;
            }

            String stringCellValue1 = row.getCell(1).getStringCellValue();
            String stringCellValue2 = row.getCell(2).getStringCellValue();
            System.out.println(stringCellValue1+"--->"+stringCellValue2);
        }

        xxsworkbook.close();
        fileInputStream.close();
    }
}
